﻿using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Yonkly.Models;
using Yonkly.Utility;
using JsonResult=Yonkly.Models.JsonResult;

namespace Yonkly.Controllers
{
    public class FriendsController : BaseController
    {
        protected override void HandleUnknownAction(string username)
        {
            //get friends
            View(username, 0);
        }

        public ActionResult View(string username, int? page)
        {
            page = page ?? 0;
            using (YonklyDataContext dc = new YonklyDataContext())
            {
                BaseViewData baseViewData = GetBaseViewData(username);
                var query = (from f in dc.Friends
                             where f.User.UserName == username
                             select new FriendItem(baseViewData)
                                        {
                                            Email = f.FriendUser.Membership.Email,
                                            UserName = f.FriendUser.UserName,
                                            UserId = f.FriendUser.UserId,
                                            Message =
                                                dc.ViewMessages.Count(vm => vm.SenderId == f.FriendId) == 0
                                                    ? null
                                                    : new MessageItem(baseViewData,
                                                                      dc.ViewMessages.Where(
                                                                          vm => vm.SenderId == f.FriendId).
                                                                          OrderByDescending(m => m.CreatedOn).First())
                                        });
                return View("View", new FriendsViewData(baseViewData)
                                       {
                                           Friends =
                                               query.ToPagedList((int) page, Globals.PageSize)
                                       });
            }
        }

        public ActionResult Invite(string email)
        {
            JsonResult result = new JsonResult();
            try
            {
                if (!Globals.IsValidEmail(email))
                {
                    result.isSuccessful = false;
                    result.errorMessage = "Invalid email address";
                }else
                {
                    //send invitation email
                    SendInviteMail(email);
                    //save invitation to database
                    using (var dc = new YonklyDataContext())
                    {
                        Invitation invitation = new Invitation();
                        if (IsUserAuthenticated)
                        {
                            invitation.Sender = LoggedInUserId;
                        }
                        invitation.Recipient = email;
                        invitation.DateSent = DateTime.Now.ToUniversalTime();
                        dc.Invitations.InsertOnSubmit(invitation);
                        dc.SubmitChanges();
                    }
                    result.isSuccessful = true;
                }
            }
            catch 
            {
                result.isSuccessful = false;
                result.errorMessage = "Failed to send invitation";
            }
            return View("Json", result);
        }

        private void SendInviteMail(string email)
        {
            const string CacheKey = "invitationMailTemplate";

            string body = HttpContext.Cache[CacheKey] as string;

            if (body == null)
            {
                string file = System.Web.HttpContext.Current.Server.MapPath("~/content/MailTemplates/invitation.txt");
                body = File.ReadAllText(file);

                if (HttpContext.Cache[CacheKey] == null)
                {
                    HttpContext.Cache[CacheKey] = body;
                }
            }

            body = body.Replace("<%friend%>", LoggedInUserName);
            body = body.Replace("<%friendurl%>", string.Format("{0}/{1}", Globals.SiteUrl, LoggedInUserName));

            SendMail(email, "Yonkly.com: Invitation", body);
        }


        /// <summary>
        /// Is the userid already following friendid
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="friendId"></param>
        /// <returns></returns>
        [NonAction]
        public static bool IsFriend(Guid UserId, Guid friendId)
        {
            using (YonklyDataContext dc = new YonklyDataContext())
            {
                var query = from friends in dc.Friends
                            where friends.UserId == UserId &&
                                  friends.FriendId == friendId
                            select new { friends.Id, friends.UserId, friends.FriendId };
                if (query.Count() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }
}